/**
 * @file        obs_daemon.c
 *
 * @brief       OpenBSD system programming study material
 *
 * @description To study system calls, process, thread, timer, signal, IPC,
 *              etc.
 *
 * @author      Kevin Zhang (kevin.misc.10@gmail.com)
 * @data        2012/12/15
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/wait.h>

#define DAEMON_INTERVAL    3

static void
obs_daemon(void)
{
    pid_t my_pid;
    pid_t my_ppid;  /* my parent's pid */

    static int cycle = 0;

    clock_t begin, end;
    double sec_elapsed;

    my_pid = getpid();
    my_ppid = getppid();
    printf("\n%s(): STARTED, my pid %d my parent's pid %d", __func__, my_pid,
            my_ppid);

    while (1) {
        /* CPU cycles used */
        begin = clock();
        printf("\n%s(): %d", __func__, __LINE__);

        end = clock();
        sec_elapsed = ((double)(begin - end)) / CLOCKS_PER_SEC;

        printf("\n%s(): %d Elapsed secs %f", __func__, __LINE__, sec_elapsed);

        sleep(DAEMON_INTERVAL);
        if (cycle++ > 2) {
            break;
        }
    }

    /* -DNDEBUG */
    assert(0);

    _exit(0);
}

int
obs_daemon_init(void)
{
    int rc;
    pid_t pid;

    if ((pid = fork()) == 0) {  /* child */
        printf("\n[OBSDAEMON] child created pid %d", pid);
        obs_daemon();
    } else if (pid > 0) {       /* parent */
        printf("\n parent %d", pid);
        if (waitpid(pid, &rc, 0) != pid) {
            rc = -1;
        }
    } else {                    /* Error */
        printf("\n Failed to fork() %d", pid);
    }

    return rc;
}

